import React from 'react'
import { Link } from 'react-router-dom'
import { inject, observer } from 'mobx-react'
import { Tree, Button, Spin, Col, Row, message, Modal, Form} from 'antd'
import './classify.css'
import ClassifyForm from './ClassifyForm'
const TreeNode = Tree.TreeNode

@inject('classifyStore', 'store')@observer
class Classify extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      loading: false,
      visible: false,
      staus: '',
      nodeInfo: {}
    }
  }

  componentDidMount () {
    this.props.classifyStore.getCategoryList({})
  }

  //节点排序
  handleCategorySort = (prop) => {
    return function (obj1, obj2) {
      var val1 = obj1[prop];
      var val2 = obj2[prop];
      if (val1 < val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    }
  }

  //将返回数组转成树状结构
  handleCategoryData = (data) => {
    let _data = []
    data = data.slice()
    data.forEach(item => {
      item.label = `${item.categoryId} ${item.categoryName}`
      item.key = item.categoryId + ''
      if(item.level === 1) {
        item.children = data.filter(_item => _item.parentCategoryId === item.categoryId)
        item.children.sort(this.handleCategorySort('seqNo'))
        _data.push(item)
      }
    })
    return _data.sort(this.handleCategorySort('seqNo'))
  }

  //验证类别名称是否重复
  handleValidateName = (name) => {
    return this.props.classifyStore.categoryList.find(item => item.categoryName === name)
  }

  handleModalShow = (params) => {
    this.setState(Object.assign({
      visible: true,
      nodeInfo: {},
    }, params))
  }

  handleModalHide = () => {
    this.setState({
      visible: false
    })
  }

  //提交表单
  handleSubmit = (values) => {
    let action = null
    if(this.state.status === 'insert') {
      values.parentCategoryId = this.state.nodeInfo.categoryId || 0
      action = this.props.classifyStore.insertCategory
    } else {
      values.categoryId = this.state.nodeInfo.categoryId
      action = this.props.classifyStore.updateCategory
    }
    return action(values).then(res => {
      if(res.status === 200 ) {
        message.success(res.data);
        this.props.classifyStore.getCategoryList({})
        this.setState({
          visible: false
        })
      } else {
        message.error(res.err);
      }
      return res;
    })
  }

  //禁用节点
  handleDeleteConfirm = (node) => {
    const _this = this;
    this.setState({
      status: 'update',
      nodeInfo: node,
    })
    Modal.confirm({
      title: `确认${node.flag === 0 ? '启用' : '禁用'}分类：${node.categoryName}？`,
      content: node.flag === 1 ? '禁用将导致类别下的商品全部下架' : '',
      onOk() {
        _this.handleSubmit({
          categoryId: node.categoryId,
          flag: node.flag === 0 ? 1 : 0
        })
      },
      onCancel() {},
    });
  }


  onDragEnter = (info) => {
    //console.log(info);
    // expandedKeys 需要受控时设置
    // this.setState({
    //   expandedKeys: info.expandedKeys,
    // });
  }
  onDrop = (info) => {
    const { categoryList, updateCategorySort, getCategoryList } = this.props.classifyStore
    const dragKey = info.dragNode.props.eventKey;
    const dropKey = info.node.props.eventKey;
    const dragPos = info.dragNode.props.pos.split('-');
    const dropPos = info.node.props.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
    const loop = (data, key, callback) => {
      data.forEach((item, index, arr) => {
        if (item.key === key) {
          return callback(item, index , arr);
        }
        if (item.children) {
          return loop(item.children, key, callback);
        }
      });
    };
    if(!info.dropToGap) {
      message.error("不能添加到该类别")
    } else {
      if(dragPos.length !== dropPos.length || (dragPos[1] !== dropPos[1] && dragPos.length === 3)) {
        message.error("不能进行此操作")
      } else {
        let data = this.handleCategoryData(categoryList),
            _data, dragObj, ar, i;
        loop(data, dragKey, (item, index, arr) => {
          arr.splice(index, 1);
          dragObj = item;
        });
        loop(data, dropKey, (item, index, arr) => {
          ar = arr;
          i = index;
        });
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj);
        } else {
          ar.splice(i + 1, 0, dragObj);
        }
        _data = ar.map((item, index) => ({
          categoryId: item.categoryId,
          seqNo: index
        }))
        updateCategorySort(_data).then(res => {
          if (res.status === 200) {
            message.success(res.data);
            getCategoryList({})
          } else {
            message.error(res.err);
          }
        })
      }
    }
  }

  render() {
    const { categoryList, loading, buttonLoading } = this.props.classifyStore
    const nodeTitle = node => (
      <Row>
        <Col span={8}>{`${node.label} ${node.memo ? '['+node.memo + ']' : ''}`}</Col>
        <Col span={8}></Col>
        <Col span={8} style={{textAlign: 'right'}}>
          { node.level === 1 ?
              <a className="m_r20"
                 onClick={() => this.handleModalShow({
                  nodeInfo: node,
                  status: 'insert'
                 })}>新增子节点</a> : null
          }
          <a className="m_r20"
             onClick={() => this.handleModalShow({
               nodeInfo: node,
               status: 'update'
             })}>修改</a>
          <a onClick={() => this.handleDeleteConfirm(node)}>{node.flag === 1 ? '禁用' : '启用'}</a>
        </Col>
      </Row>
    )
    const loop = data => data.map((item) => {
      if (item.children && item.children.length) {
        return <TreeNode key={item.key} title={nodeTitle(item)}>{loop(item.children)}</TreeNode>;
      }
      return <TreeNode key={item.key} title={nodeTitle(item)}/>;
    });
    return (
      <div>
        {this.props.store.collapse ?
            <h2 style={{marginBottom: 16}}>
              <Link to="/classify">商品分类</Link>
            </h2> : null
        }
        <div className="table-operations">
          <Button type="primary"
                  onClick={() => this.handleModalShow({
                    status: 'insert'
                  })}>新增分类</Button>
          {/*<Button>批量导入</Button>*/}
        </div>
        <Spin spinning={loading} style={{minHeight: 600}}>
          <Tree
              className="draggable-tree node_tree"
              draggable
              onDragEnter={this.onDragEnter}
              onDrop={this.onDrop}
              >
            {loop(this.handleCategoryData(categoryList))}
          </Tree>
        </Spin>
        <ClassifyForm
            visible={this.state.visible}
            loading={buttonLoading}
            status={this.state.status}
            nodeInfo={this.state.nodeInfo}
            validateName = {this.handleValidateName}
            onCancel={this.handleModalHide}
            onSubmit={this.handleSubmit}/>
      </div>
    );
  }
}

export default Classify
